package com.xinghou.platform.file.model;

import org.apache.commons.chain.impl.ContextBase;
import org.springframework.http.ResponseEntity;


public class ResourceContext<T, E> extends ContextBase {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -1207199646753687255L;

	private ResourceContent source;
	
	private ResourceContent extars[];
	
	private BaseResponse<E> response = new BaseResponse<E>();
	
	private BaseRequst<T> request = new BaseRequst<T>();
	
	public ResourceContext(){
		source = new ResourceContent();
	}
	
	public ResourceContext(int extraCount){
		source = new ResourceContent();
		if(extraCount > 0){
			extars = new ResourceContent[extraCount];
			for(int i=0;i<extraCount;i++){
				ResourceContent extra = new ResourceContent();
				extars[i] = extra;
			}
		}
	}
	
	public ResourceContext(String rootPath, int extraCount){
		source = new ResourceContent(rootPath);
		if(extraCount > 0){
			extars = new ResourceContent[extraCount];
			for(int i=0;i<extraCount;i++){
				ResourceContent extra = new ResourceContent(rootPath);
				extars[i] = extra;
			}
		}
	}
	
	public void setRootPath(String rootPath, boolean flag){
		source.setRootPath(rootPath);
		if(flag){
			if(extars != null && extars.length >0){
				for(ResourceContent r:extars){
					if(r!=null)
						r.setRootPath(rootPath);
				}
			}
		}
	}
	
	public void setSubPath(String subPath, boolean flag){
		source.setSubPath(subPath);
		if(flag){
			if(extars != null && extars.length >0){
				for(ResourceContent r:extars){
					if(r!=null)
						r.setSubPath(subPath);
				}
			}
		}
	}
	
	public void setResourceName(String resourceName, boolean flag){
		source.setResourceName(resourceName);
		if(flag){
			if(extars != null && extars.length >0){
				for(ResourceContent r:extars){
					if(r!=null)
						r.setResourceName(resourceName);
				}
			}
		}
	}
	
	public ResourceContent getSource() {
		return source;
	}

	public ResourceContent[] getExtars() {
		return extars;
	}

	public void clear(){
		request = null;
		source = null;
		extars = null;
		response = null;
	}
	
	public BaseResponse<E> getResponse(){
		return response;
	}
	
	public BaseRequst<T> getRequest(){
		return request;
	}
	
	public ResponseEntity<E> response(){
		try{
			return new ResponseEntity<E>(response.getBody(), response.getResponseHeaders(), response.getStatusCode());
		}finally{
			clear();
		}
	}

}
